package com.jcfk.system.service;

import com.jcfk.system.domain.po.SysBusinessGroup;
import com.jcfk.system.domain.po.SysBusinessGroupUser;
import com.jcfk.system.domain.po.SysUser;
import com.jcfk.system.domain.query.SysBusinessGroupQuery;
import com.jcfk.system.domain.dto.SysBusinessGroupDTO;
import com.jcfk.system.dao.SysBusinessGroupDao;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import com.jcfk.common.core.utils.BeanUtils;
import cn.hutool.core.util.StrUtil;
import com.jcfk.common.security.utils.SecurityUtils;
import com.alibaba.druid.util.StringUtils;

import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.stream.Collectors;

import com.jcfk.common.core.utils.IdUtils;


import java.util.Date;

/**
 * @author awei
 * @email 522891237@gqq.com
 * @date 2023-12-27
 */
@Service
public class SysBusinessGroupService extends BaseService<SysBusinessGroupDao, SysBusinessGroup> {

    @Autowired
    private SysBusinessGroupUserService sysBusinessGroupUserService;

    @Autowired
    private SysUserService sysUserService;

    /**
     * SysBusinessGroup分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<SysBusinessGroupDTO> queryByPage(DataPage<SysBusinessGroupDTO> page, SysBusinessGroupQuery query) {
        // 分页查询
        query.setName(StringUtils.isEmpty(query.getName()) ? query.getName() :"%" + query.getName() + "%");
        page = this.baseMapper.queryByPage(page, query);
        return page;
    }


    /**
     * 判断SysBusinessGroup是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(SysBusinessGroupDTO dto) {
        QueryWrapper<SysBusinessGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0);

        return RetResult.ok();
    }

    /**
     * 插入
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(SysBusinessGroupDTO dto) {

        // 保存
        SysBusinessGroup item = new SysBusinessGroup();
        BeanUtils.copyProperties(dto, item);
        this.setDefaultValue(item);
        super.save(item);

        // 添加用户
        if (dto.getUserIds().size() > 0) {
            List<SysBusinessGroupUser> list = new ArrayList<>();
            for (String userId : dto.getUserIds()) {
                SysBusinessGroupUser sysBusinessGroupUser = new SysBusinessGroupUser();
                sysBusinessGroupUser.setBusinessId(item.getId());
                sysBusinessGroupUser.setUserId(userId);
                sysBusinessGroupUserService.setDefaultValue(sysBusinessGroupUser);
                list.add(sysBusinessGroupUser);

            }
            // 添加保存
            sysBusinessGroupUserService.saveBigBatch(list);
        }
    }

    /**
     * 更新
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(SysBusinessGroupDTO dto) {

        // 保存
        SysBusinessGroup item = new SysBusinessGroup();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);

        // 删除原用户
        QueryWrapper<SysBusinessGroupUser> sysBusinessGroupUserQueryWrapper = new QueryWrapper<>();
        sysBusinessGroupUserQueryWrapper.lambda().eq(SysBusinessGroupUser::getBusinessId, item.getId());
        SysBusinessGroupUser businessGroupUser = new SysBusinessGroupUser();
        businessGroupUser.setDeleted(1);
        sysBusinessGroupUserService.update(businessGroupUser, sysBusinessGroupUserQueryWrapper);

        // 添加用户
        if (dto.getUserIds().size() > 0) {
            List<SysBusinessGroupUser> list = new ArrayList<>();
            for (String userId : dto.getUserIds()) {
                SysBusinessGroupUser sysBusinessGroupUser = new SysBusinessGroupUser();
                sysBusinessGroupUser.setBusinessId(item.getId());
                sysBusinessGroupUser.setUserId(userId);
                sysBusinessGroupUserService.setDefaultValue(sysBusinessGroupUser);
                list.add(sysBusinessGroupUser);
            }
            // 添加保存
            sysBusinessGroupUserService.saveBigBatch(list);
        }

        super.updateById(item);
    }

    /**
     * 根据批量主键删除(逻辑删除)
     *
     * @param dto
     * @return bool
     */
    @Transactional(rollbackFor = Exception.class)
    public Boolean logicDeleteList(SysBusinessGroupDTO dto) {

        SysBusinessGroup item = new SysBusinessGroup();

        this.setDefaultValue(item);
        item.setDeleted(1);

        QueryWrapper<SysBusinessGroup> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id", dto.getIds());

        return this.update(item, queryWrapper);
    }

    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(SysBusinessGroup item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());
        item.setDeleted(0);

    }

    /**
     * 根据主键获取信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public SysBusinessGroupDTO get(String id) {
        // 查询数据
        SysBusinessGroup item = this.baseMapper.selectById(id);
        SysBusinessGroupDTO dto = new SysBusinessGroupDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        QueryWrapper<SysBusinessGroupUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysBusinessGroupUser::getBusinessId, id);
        queryWrapper.lambda().eq(SysBusinessGroupUser::getDeleted, 0);
        List<SysBusinessGroupUser> sysBusinessGroupUsers = sysBusinessGroupUserService.list(queryWrapper);
        List<String> userIds = new ArrayList<>();
        for (SysBusinessGroupUser sysBusinessGroupUser : sysBusinessGroupUsers) {
            userIds.add(sysBusinessGroupUser.getUserId());
        }

        dto.setUserIds(userIds);

        // 用户回显
        if (userIds.size() > 0) {
            QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
            sysUserQueryWrapper.select("id, first_name firstName").in("id", userIds);
            List<Map<String, Object>> users = sysUserService.listMaps(sysUserQueryWrapper);
            dto.setUsers(users);
        }

        return dto;
    }
}

